using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Net;
using wicpowerTcpTool.Models;

namespace wicpowerTcpTool.Config
{
    public static class ConfigManager
    {
        private static readonly string jsonConfigPath = "config.json";
        private static readonly string iniConfigPath = "bin/Debug/config.ini";

        public static List<string> LoadAllConfigs()
        {
            var configs = new List<string>();
            
            if (File.Exists(iniConfigPath))
            {
                var iniContent = File.ReadAllText(iniConfigPath);
                var sections = iniContent.Split(new[]{"\r\n\r\n", "\n\n"}, StringSplitOptions.RemoveEmptyEntries);
                configs.AddRange(sections.Where(s => s.StartsWith("[ForwardGroup_")));
            }
            
            return configs;
        }

        public static ForwardGroup LoadForwardGroupConfig(string iniSection)
        {
            try
            {
                var lines = iniSection.Split('\n').Where(l => !string.IsNullOrWhiteSpace(l));
                var config = new Dictionary<string, string>();
                
                foreach (var line in lines.Skip(1)) // Skip section header
                {
                    var parts = line.Split(new[] {'='}, 2);
                    if (parts.Length == 2)
                    {
                        config[parts[0].Trim()] = parts[1].Trim();
                    }
                }

                if (!config.ContainsKey("Port1") || !config.ContainsKey("Port2"))
                    return null;

                int port1 = int.Parse(config["Port1"]);
                int port2 = int.Parse(config["Port2"]);
                string remark = config.ContainsKey("Remark") ? config["Remark"] : "";
                string authToken = config.ContainsKey("AuthToken") ? config["AuthToken"] : "";
                IPAddress ip = config.ContainsKey("ListenIP") ? 
                    IPAddress.Parse(config["ListenIP"]) : IPAddress.Any;

                return new ForwardGroup(0, port1, port2, remark, authToken, ip);
            }
            catch
            {
                return null;
            }
        }

        public static IPAddress GetDefaultListenIP()
        {
            try
            {
                var configs = LoadAllConfigs();
                if (configs.Count > 0)
                {
                    var firstConfig = LoadForwardGroupConfig(configs.First());
                    return firstConfig?.ListenIP ?? IPAddress.Any;
                }
            }
            catch { }
            
            return IPAddress.Any;
        }

        public static void SaveForwardGroupConfig(IPAddress ip, int port1, int port2, string remark, string authToken)
        {
            try
            {
                var section = $"[ForwardGroup_{DateTime.Now:yyyyMMddHHmmss}]\n" +
                              $"ListenIP={ip}\n" +
                              $"Port1={port1}\n" +
                              $"Port2={port2}\n" +
                              $"Remark={remark}\n" +
                              $"AuthToken={authToken}\n\n";
                
                File.AppendAllText(iniConfigPath, section);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存INI配置失败: {ex.Message}");
            }
        }

        public static async Task<AppConfig> LoadConfigAsync()
        {
            if (!File.Exists(jsonConfigPath))
            {
                return new AppConfig();
            }

            try
            {
                using FileStream fs = File.OpenRead(jsonConfigPath);
                var config = await JsonSerializer.DeserializeAsync<AppConfig>(fs);
                return config ?? new AppConfig();
            }
            catch (Exception)
            {
                return new AppConfig();
            }
        }

        public static async Task SaveConfigAsync(AppConfig config)
        {
            try
            {
                using FileStream fs = File.Create(jsonConfigPath);
                var options = new JsonSerializerOptions { WriteIndented = true };
                await JsonSerializer.SerializeAsync(fs, config, options);
            }
            catch (Exception ex)
            {
                throw new Exception("保存配置文件失败: " + ex.Message);
            }
        }
    }
}
